<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Banner extends Model
{
    use HasFactory;

    protected $fillable = [
        'title',
        'description',
        'image',
        'link',
        'sort_order',
        'is_active'
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'sort_order' => 'integer'
    ];

    // 获取图片URL
    public function getImageUrlAttribute()
    {
        if ($this->image) {
            // 如果图片路径已经是完整URL，直接返回
            if (str_starts_with($this->image, 'http')) {
                return $this->image;
            }
            // 如果图片路径以/开头，直接返回
            if (str_starts_with($this->image, '/')) {
                return $this->image;
            }
            // 否则作为相对路径处理
            return '/' . ltrim($this->image, '/');
        }
        return '/images/banners/default.jpg';
    }

    // 作用域：只获取活跃的轮播图
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    // 作用域：按排序顺序排列
    public function scopeOrdered($query)
    {
        return $query->orderBy('sort_order')->orderBy('created_at', 'desc');
    }
}
